<template>
	<el-container>

		<el-aside width="200px" v-loading="showGrouploading">
			<el-container>
				<el-header>
					<el-input placeholder="输入关键字进行过滤" v-model="groupFilterText" clearable></el-input>
				</el-header>
				<el-main class="nopadding">
					<el-tree ref="group" class="menu" node-key="id" :data="group" :current-node-key="''"
							 :highlight-current="true" :expand-on-click-node="false"
							 :filter-node-method="groupFilterNode" @node-click="groupClick"></el-tree>
				</el-main>
			</el-container>
		</el-aside>
		<el-container>

			<el-header>
				<div class="left-panel">
					<el-button type="primary" icon="el-icon-plus" @click="add"></el-button>
<!--					<el-button type="primary" plain :disabled="selection.length==0||selection.length > 1"-->
<!--							   @click="changeRole()">分配角色-->
<!--					</el-button>-->
					<el-button type="primary" plain :disabled="selection.length==0||selection.length > 1"
							   @click="restPwd()">密码重置
					</el-button>
				</div>
				<div class="right-panel">
					<div class="right-panel-search">
						<el-input v-model="search.name" placeholder="登录账号 / 姓名" clearable></el-input>
						<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
					</div>
				</div>
			</el-header>
			<el-main class="nopadding">

				<scTable ref="table" :apiObj="apiObj"  :params="params" @selection-change="selectionChange" stripe remoteSort
						 remoteFilter>
					<el-table-column type="selection" width="50"></el-table-column>

					<el-table-column label="真实名称" prop="realName" width="100"
									 column-key="filterUserName"></el-table-column>
					<el-table-column label="账号" prop="staffName" width="150" sortable='custom'></el-table-column>
					<el-table-column label="邮箱" prop="staffEmail" width="170" sortable='custom'></el-table-column>
					<el-table-column label="性别" prop="staffSex" width="80">
						<template #default="scope">
							<span v-if="scope.row.staffSex == 0">男</span>
							<span v-if="scope.row.staffSex == 1">女</span>
						</template>
					</el-table-column>
					<el-table-column label="电话" prop="staffPhone" width="170" sortable='custom'></el-table-column>

					<el-table-column label="是否启用" prop="enable" width="80">
						<template #default="scope">
							<el-switch v-model="scope.row.enable" @change="changeSwitch($event, scope.row)"
									   :loading="scope.row.$switch_status" :active-value="0"
									   :inactive-value="1"></el-switch>
						</template>
					</el-table-column>

					<el-table-column label="操作" fixed="right" align="center" width="200">
						<template #default="scope">
							<el-button-group>
								<el-button text type="primary" size="small" @click="table_show(scope.row, scope.$index)">查看
								</el-button>
								<el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">编辑
								</el-button>
								<el-button text type="primary" size="small" @click="changeRole(scope.row)">分配角色
								</el-button>
							</el-button-group>
						</template>
					</el-table-column>
				</scTable>
			</el-main>
		</el-container>
	</el-container>

	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>
	<send-dialog v-if="dialog.send" ref="sendDialog" @success="handleSuccess"
				 @closed="dialog.save=false"></send-dialog>
	<edit-dialog v-if="dialog.edit" ref="editDialog" @success="handleSuccess"
				 @closed="dialog.edit=false" @guanbi="close"></edit-dialog>
</template>

<script>

    import saveDialog from './emp'
    import sendDialog from './send'
    import editDialog from './edit'


    export default {
        name: 'user',
        components: {
            saveDialog,
            sendDialog,
            editDialog,
        },
        data() {
            return {
                dialog: {
                    save: false,
                    send: false,
                    edit: false
                },
                showGrouploading: false,
                groupFilterText: '',
                group: [],
                apiObj: this.$API.user.user.list,
				roleOptions: [],
                selection: [],
                search: {},
                params: {},
				node: {}
            }
        },
        watch: {
            groupFilterText(val) {
                this.$refs.group.filter(val);
            }
        },

        mounted() {
            this.getGroup()
        },
        async created() {
            var res = await this.$API.user.role.list.post();
            if (res && res.code == 0) {
                this.roleOptions = res.data;
            }
        },
        methods: {
            //添加
            add() {
                if (!this.node.data) {
                    this.$message.warning('未选择部门')
                    return false
                }
                this.dialog.save = true
                this.$nextTick(() => {
                    this.$refs.saveDialog.open().setData(this.node.data)
                })
            },
            //密码重置
            async restPwd() {
                let data = {
                    staffNumber: this.selection[0].staffNumber
                }
                var res = await this.$API.user.user.restPwd.post(data);
                if (res && res.code == 0) {
                    this.$message.success("密码重置成功")
                }
            },
            //分配角色
            changeRole(row) {
                this.dialog.send = true
                this.$nextTick(() => {
                    this.$refs.sendDialog.open('send').setData(row, this.roleOptions)
                })
            },
            //编辑
            table_edit(row) {
                this.dialog.edit = true
                this.$nextTick(() => {
                    this.$refs.editDialog.open('edit').setData(row)
                })
            },
            //表格内开关
            async changeSwitch(val, row) {
                row.enable = row.enable == 1 ? 0 : 1
                row.$switch_status = true;
                let data = {
                    enable: val,
                    staffNumber: row.staffNumber
                }
                var res = await this.$API.user.user.enable.post(data);
                if (res && res.code == 0) {
                    setTimeout(() => {
                        delete row.$switch_status;
                        row.enable = val;
                        // console.log(typeof val, row)
                        this.$message.success("操作成功")
                    }, 500)
                }

            },

            //查看
            table_show(row) {
                this.dialog.save = true
                this.$nextTick(() => {
                    this.$refs.saveDialog.open('show').setData(row)
                })
            },
            //删除
            async table_del(row, index) {
                var reqData = {id: row.id}
                var res = await this.$API.user.userDeleteById.post(reqData);
                if (res.code == 0) {
                    //这里选择刷新整个表格 OR 插入/编辑现有表格数据
                    this.$refs.table.tableData.splice(index, 1);
                    this.$message.success(res.data)
                }
            },
            //批量删除
            async batch_del() {
                this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
                    type: 'warning'
                }).then(() => {
                    const loading = this.$loading();
                    this.selection.forEach(item => {
                        this.$refs.table.tableData.forEach((itemI, indexI) => {
                            if (item.id === itemI.id) {
                                this.$refs.table.tableData.splice(indexI, 1)
                            }
                        })
                    })

                    this.batch_delte()

                    loading.close();
                    // this.$message.success("操作成功")
                }).catch(() => {

                })
            },
            //批量删除接口
            async batch_delte() {
                const arr = []
                this.selection.forEach(item => {
                    var reqData = {id: item.id}
                    arr.push(reqData)
                })
                // var reqData = {id: row.id}
                var res = await this.$API.user.userDelBatch.post(arr);
                if (res.code == 0) {
                    //这里选择刷新整个表格 OR 插入/编辑现有表格数据
                    this.$message.success(res.data)
                }
            },
            //表格选择后回调事件
            selectionChange(selection) {
                this.selection = selection;
            },
            //加载树数据
            async getGroup() {
                this.showGrouploading = true;
                var res = await this.$API.user.dept.list.post();
                this.showGrouploading = false;
                // var allNode = {id: '', label: '所有'}
                // res.data.unshift(allNode);
                this.group = res.data;
            },
            //树过滤
            groupFilterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            //树点击事件
            groupClick(data) {
                let orgIds = [];
                orgIds.push(data.id);
                var node = this.$refs.group.getNode(data);
                this.node = node
                this.getTree(node.data , orgIds)
                this.params.orgIds = orgIds;
                this.params.realName = this.search.realName;
                this.params.staffPhone = this.search.staffPhone;
                this.$refs.table.reload(this.params)
            },
            getTree(node , orgIds) {
                if(node.children === null ||  node.children.length == 0){
                    orgIds.push(node.id);
                }else{
                    orgIds.push(node.id);
                    node.children.forEach(item => {
                        this.getTree(item, orgIds)
                    })
                }
            },
            //搜索
            upsearch() {
                this.$refs.table.upData(this.search)
            },
            //本地更新数据
            handleSuccess(data, mode) {
                if (mode == 'add') {
                    data.id = new Date().getTime()
                    this.$refs.table.tableData.unshift(data)
                } else if (mode == 'edit') {
                    this.$refs.table.tableData.filter(item => item.id === data.id).forEach(item => {
                        Object.assign(item, data)
                    })
                }
            }
        }
    }
</script>

<style>
</style>
